package com.example.springboot.v2.mapping;

import com.example.springboot.mapping.ApiVersion;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.servlet.mvc.condition.RequestCondition;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;

/**
 * 创建自定义requestMapping类来配置规则
 *
 * @author by Mr. Li 2021/1/30 18:10
 */
public class CustomRequestMappingHandlerMapping extends RequestMappingHandlerMapping {
    @Override
    protected RequestCondition<?> getCustomMethodCondition(Method method) {
        final ApiVersion annotation = AnnotationUtils.findAnnotation(method, ApiVersion.class);
        return getApiVersionAnnotation(annotation);
    }

    @Override
    protected RequestCondition<?> getCustomTypeCondition(Class<?> handlerType) {
        final ApiVersion annotation = AnnotationUtils.findAnnotation(handlerType, ApiVersion.class);
        return getApiVersionAnnotation(annotation);
    }

    /**
     * 容器在加载会加载所有请求映射的信息{@link RequestMappingHandlerMapping#createRequestMappingInfo(java.lang.reflect.AnnotatedElement)}
     * 机会调用该方法，获取所有的请求
     *
     * @param version
     * @return
     */
    private RequestCondition<?> getApiVersionAnnotation(ApiVersion version) {
        return version != null ? new ApiVersionCondition(version.version()) : null;
    }
}
